package com.heima.article.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.ObjectUtil;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.article.mapper.ArticleConfigMapper;
import com.heima.article.mapper.ArticleContentMapper;
import com.heima.article.mapper.ArticleMapper;
import com.heima.article.service.ArticleFreemarkerService;
import com.heima.article.service.ArticleService;
import com.heima.common.redis.CacheService;
import com.heima.common.constants.ArticleConstants;
import com.heima.common.constants.KafkaConstans;
import com.heima.common.constants.WemediaConstants;
import com.heima.common.exception.CustomException;
import com.heima.model.article.dtos.ArticleDto;
import com.heima.model.article.dtos.ArticleHomeDto;
import com.heima.model.article.pojos.ApArticle;
import com.heima.model.article.pojos.ApArticleConfig;
import com.heima.model.article.pojos.ApArticleContent;
import com.heima.model.article.vos.HotArticleVo;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.mess.ArticleVisitStreamMess;
import com.heima.model.search.vos.SearchArticleVo;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.Comparator;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author Xiao
 * @version 1.0
 * @description
 * @date 2021/11/20
 */
@Service
@Slf4j
@Transactional
public class ArticleServiceImpl extends ServiceImpl<ArticleMapper, ApArticle> implements ArticleService {
    @Autowired
    private ArticleMapper articleMapper;
    @Autowired
    private ArticleContentMapper contentMapper;
    @Autowired
    private ArticleConfigMapper configMapper;

    /**
     * 加载文章列表
     * @param articleHomeDto
     * @param type  1：加载更多  2：加载最新
     * @return
     */
    @Override
    public ResponseResult loadArticleList(ArticleHomeDto articleHomeDto, Short type) {
        if (ObjectUtil.isEmpty(articleHomeDto)) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_REQUIRE);
        }
        //分页参数校验
        Integer size = articleHomeDto.getSize();
        size = size == null || size == 0 ?
                ArticleConstants.DEFAULT_PAGE_SIZE :
                Math.min(size, ArticleConstants.MAX_PAGE_SIZE);
        articleHomeDto.setSize(size);
        //频道参数校验
        if (StringUtils.isBlank(articleHomeDto.getTag())) {
            articleHomeDto.setTag(ArticleConstants.DEFAULT_TAG);
        }
        //时间校验
        if (ObjectUtil.isEmpty(articleHomeDto.getMaxBehotTime())){
            articleHomeDto.setMaxBehotTime(new Date());
        }
        if (ObjectUtil.isEmpty(articleHomeDto.getMinBehotTime())){
            articleHomeDto.setMinBehotTime(new Date());
        }
        //type参数校验
        type = type == null ||
                !type.equals(ArticleConstants.TYPE_LOAD_MORE) ||
                !type.equals(ArticleConstants.TYPE_LOAD_NEW) ?
                ArticleConstants.TYPE_LOAD_MORE : type;
        //数据查询
        List<ApArticle> articles = articleMapper.loadArticleList(articleHomeDto, type);
        //数据校验
        if (CollUtil.isEmpty(articles)) {
            articles = new ArrayList<>();
        }
        //结果返回
        return ResponseResult.okResult(articles);
    }

    @Autowired
    private CacheService cacheService;

    /**
     * 加载文章列表
     * @param dto
     * @param type      1 加载更多   2 加载最新
     * @param firstPage true  是首页  flase 非首页
     * @return
     */
    @Override
    public ResponseResult load(ArticleHomeDto dto, Short type, boolean firstPage) {
        if(firstPage){
            String jsonStr = cacheService.get(ArticleConstants.HOT_ARTICLE_FIRST_PAGE + dto.getTag());
            if(StringUtils.isNotBlank(jsonStr)){
                List<HotArticleVo> hotArticleVoList = JSON.parseArray(jsonStr, HotArticleVo.class);
                return ResponseResult.okResult(hotArticleVoList);
            }
        }
        return loadArticleList(dto, type);
    }

    @Autowired
    private ArticleFreemarkerService freemarkerService;
    /**
     * 保存文章
     * @param dto
     * @return
     */
    @Override
    public ResponseResult saveArticle(ArticleDto dto) {
        /*try {
            System.err.println("模拟访问超时，测试feign降级保护");
            Thread.sleep(3000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }*/
        //校验参数
        if (ObjectUtil.isEmpty(dto))
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_REQUIRE);
        ApArticle article = new ApArticle();
        BeanUtil.copyProperties(dto, article);
        //判断id是否存在
        if (ObjectUtil.isEmpty(dto.getId())) {
            //不存在 --> 保存文章、文章内容、文章配置
            this.save(article);
            ApArticleContent articleContent = new ApArticleContent();
            articleContent.setArticleId(article.getId());
            articleContent.setContent(dto.getContent());
            contentMapper.insert(articleContent);
            ApArticleConfig articleConfig = new ApArticleConfig(article.getId());
            configMapper.insert(articleConfig);
        } else {
            //存在 --> 修改文章、文章内容
            this.updateById(article);
            LambdaQueryWrapper<ApArticleContent> wrapper = new LambdaQueryWrapper<>();
            wrapper.eq(ApArticleContent::getArticleId, article.getId());
            ApArticleContent articleContent = contentMapper.selectOne(wrapper);
            articleContent.setContent(dto.getContent());
            contentMapper.updateById(articleContent);
        }
        //异步生成静态模板并修改static_url字段
        ApArticle apArticle = this.getById(article.getId());
        freemarkerService.buildArticleToMinIO(apArticle, dto.getContent());
        //返回文章id
        log.info("文章发布成功，id：{}", apArticle.getId());
        return ResponseResult.okResult(apArticle.getId());
    }

    @Autowired
    private KafkaTemplate<String, String> kafkaTemplate;

    /**
     * 自媒体端上架/下架/删除文章时，同步修改app端文章
     * @param articleConfig
     * @return
     */
    @Override
    public ResponseResult delOrDownArticle(ApArticleConfig articleConfig) {
        int update = configMapper.update(articleConfig, Wrappers.<ApArticleConfig>lambdaUpdate()
                .eq(ApArticleConfig::getArticleId, articleConfig.getArticleId()));
        log.info("自媒体文章上架/下架/删除，文章id：{}", articleConfig.getArticleId());
        if (update <= 0) {
            throw new CustomException(AppHttpCodeEnum.SERVER_ERROR);
        }
        if (WemediaConstants.WM_NEWS_UP.equals(articleConfig.getIsDown())) {
            kafkaTemplate.send(KafkaConstans.SEARCH_ADD_TOPIC,
                    JSON.toJSONString(articleConfig.getArticleId()));
        } else {
            Long articleId = articleConfig.getId();
            if (ObjectUtil.isNotEmpty(articleId)) {
                ApArticle apArticle = this.getById(articleId);
                ApArticleContent articleContent = contentMapper.selectOne(
                        Wrappers.<ApArticleContent>lambdaQuery()
                        .eq(ApArticleContent::getArticleId, articleId));
                SearchArticleVo vo = new SearchArticleVo();
                BeanUtil.copyProperties(apArticle, vo);
                if (StringUtils.isNotBlank(articleContent.getContent())) {
                    vo.setContent(articleContent.getContent());
                }
                kafkaTemplate.send(ArticleConstants.ARTICLE_ES_SYNC_TOPIC,
                        JSON.toJSONString(vo));
            }
        }
        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }

    /**
     * 更新文章的分值  同时更新缓存中的热点文章数据
     * @param mess
     */
    @Override
    public void updateScore(ArticleVisitStreamMess mess) {
        //1.更新文章的阅读、点赞、收藏、评论的数量
        ApArticle apArticle = updateArticle(mess);
        //2.计算文章的分值
        Integer score = computeScore(apArticle);
        score = score * 3;
        //3.替换当前文章对应频道的热点数据
        replaceDataToRedis(apArticle, score,
                ArticleConstants.HOT_ARTICLE_FIRST_PAGE + apArticle.getChannelId());
        //4.替换推荐对应的热点数据
        replaceDataToRedis(apArticle, score,
                ArticleConstants.HOT_ARTICLE_FIRST_PAGE + ArticleConstants.DEFAULT_TAG);
    }

    /**
     * 替换数据并且存入到redis
     * @param apArticle
     * @param score
     * @param s
     */
    private void replaceDataToRedis(ApArticle apArticle, Integer score, String channel) {
        String articleListStr = cacheService.get(channel);
        if (StringUtils.isNotBlank(articleListStr)) {
            List<HotArticleVo> hotArticleVoList = JSON.parseArray(articleListStr,
                    HotArticleVo.class);

            boolean flag = true;
            //如果缓存中存在该文章，只更新分值
            for (HotArticleVo hotArticleVo : hotArticleVoList) {
                if (hotArticleVo.getId().equals(apArticle.getId())) {
                    hotArticleVo.setScore(score);
                    flag = false;
                    break;
                }
            }
            //如果缓存中不存在，查询缓存中分值最小的一条数据，进行分值的比较，
            // 如果当前文章的分值大于缓存中的数据，就替换
            if (flag) {
                if (hotArticleVoList.size() >= 30) {
                    //对缓存中的文章按分值排序
                    hotArticleVoList = hotArticleVoList.stream().
                            sorted(Comparator.comparing(HotArticleVo::getScore).reversed())
                            .collect(Collectors.toList());
                    //获取缓存中最后一条(分数最低)的文章
                    HotArticleVo lastHot = hotArticleVoList.
                            get(hotArticleVoList.size() - 1);
                    if (lastHot.getScore() < score) {
                        hotArticleVoList.remove(lastHot);
                        HotArticleVo hot = new HotArticleVo();
                        BeanUtils.copyProperties(apArticle, hot);
                        hot.setScore(score);
                        hotArticleVoList.add(hot);
                    }
                } else {
                    HotArticleVo hot = new HotArticleVo();
                    BeanUtils.copyProperties(apArticle, hot);
                    hot.setScore(score);
                    hotArticleVoList.add(hot);
                }
            }
            //缓存到redis
            hotArticleVoList = hotArticleVoList.stream()
                    .sorted(Comparator.comparing(HotArticleVo::getScore)
                            .reversed())
                    .collect(Collectors.toList());
            cacheService.set(channel, JSON.toJSONString(hotArticleVoList));
        }
    }

    /**
     * 更新文章行为数量
     * @param mess
     */
    private ApArticle updateArticle(ArticleVisitStreamMess mess) {
        ApArticle apArticle = getById(mess.getArticleId());
        apArticle.setCollection(apArticle.getCollection()==null?
                0:apArticle.getCollection()+mess.getCollect());
        apArticle.setComment(apArticle.getComment()==null?
                0:apArticle.getComment()+mess.getComment());
        apArticle.setLikes(apArticle.getLikes()==null?
                0:apArticle.getLikes()+mess.getLike());
        apArticle.setViews(apArticle.getViews()==null?
                0:apArticle.getViews()+mess.getView());
        updateById(apArticle);
        return apArticle;
    }

    /**
     * 计算文章的具体分值
     * @param apArticle
     * @return
     */
    private Integer computeScore(ApArticle apArticle) {
        Integer score = 0;
        if(apArticle.getLikes() != null){
            score += apArticle.getLikes() *
                    ArticleConstants.HOT_ARTICLE_LIKE_WEIGHT;
        }
        if(apArticle.getViews() != null){
            score += apArticle.getViews();
        }
        if(apArticle.getComment() != null){
            score += apArticle.getComment() *
                    ArticleConstants.HOT_ARTICLE_COMMENT_WEIGHT;
        }
        if(apArticle.getCollection() != null){
            score += apArticle.getCollection() *
                    ArticleConstants.HOT_ARTICLE_COLLECTION_WEIGHT;
        }
        return score;
    }
}